import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import { FormattedMessage } from 'umi-plugin-react/locale';
import Ellipsis from '@/components/Ellipsis';
import { Row, Col, Card, Button, Table, Pagination, Modal, message, Input, Icon, List, Avatar, Spin } from 'antd';
import styles from './index.less';
import del1Img from '@/assets/knowledge/del1.png';
import editImg from '@/assets/knowledge/edit.png';
import RobotBtn from '@/utils/robotBtn';
import Bottword from '@/modules/Bottword.js';
import addJKImg from '@/assets/dialog/addJK.png';

const confirm = Modal.confirm;
const ApiServiceCondition = React.lazy(() => import('./apiServiceCondition'));
@connect(({ customApi, loading }) => ({
  customApi,
  loading: loading.effects['customApi/fetch'],
}))

class CustomApi extends Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      limit: 14,
      currentApiId: null,
      apiNames: null,
      tableLoading: true,
      list:[],
      total:0,
      apiServiceConditionShow:false,
      apiTitle:'',
      apiId:'',
      apiLoading:false
    };
  }


  componentDidMount() {
    this.fetchApiListById()
  }

  fetchApiListById=()=>{
    const that = this;
    const newPage = that.state.page;
    const newLimit = that.state.limit;
    const newApiNames = that.state.apiNames;
    const { dispatch, currentUser } = this.props;
    // TODO 这个地方currentUser可能会为空，需要加以判断
    console.log(currentUser);
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/fetch',
        payload: { robotId: currentUser.robotId, page: newPage, limit: newLimit,apiNames: newApiNames },
        callback:(res)=>{
          this.setState({
            tableLoading: false,
            list:res.list,
            total:parseInt(res.total)
          })
        }
      });
    });
  };

  delApiById(_id){
    const that = this;
    const { dispatch } = that.props;
    that.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/delete',
        payload: {id: _id },
        callback: (res)=>{
          if(res.msg){
            message.info(res.msg);
            that.fetchApiListById()
          }
        }
      });
    });
  }

  editApi(id) {
    const { dispatch } = this.props;
    console.log(id)
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/redirect',
        payload: {apiId:id},
      });
    });
  }

  delApi(id) {
    const  that = this;
    confirm({
      title: '删除任务',
      content: '确认删除该API接口吗？',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        that.delApiById(id)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  setApiName(val){
      this.setState({
        apiNames:val,
        tableLoading: true
      },()=>{
      this.fetchApiListById()
    });
  }

  addApi(){
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/redirect',
        payload: { },
      });
    });
  }

  // 翻页
  fanye(e) {
    this.setState({
      page: e,
      tableLoading: true
    }, () => {
      this.fetchApiListById();
    });
  };

  showApiServiceConditionShow=(apiId,name)=>{
    this.setState({
      apiServiceConditionShow:true,
      apiLoading:true,
      apiTitle:name,
      apiId
    })
  };

  hideApiServiceConditionShow=()=>{
    this.setState({
      apiServiceConditionShow:false,
      apiId:''
    })
  };

  render() {
    const {
      list,
      loading,
      total,limit,apiServiceConditionShow,apiTitle,apiId,apiLoading
    } = this.state;

    return (
      <GridContent>
        <Suspense fallback={<PageLoading />}>
            <div className={styles.cardList}>
              <p style={{marginTop:10}} className={styles.pageTitle}>接口管理</p>
              <List style={{maxHeight:'100%',overflowY:'auto',overflowX:'hidden'}}
                rowKey="id"
                loading={loading}
                // pagination={{
                //   onChange: page => {
                //     this.fanye(page)
                //   },
                //   pageSize: 24,
                //   total,
                // }}
                grid={{ gutter: 24, lg: 3,  sm: 2, xs: 1 }}
                dataSource={['',...list]}
                renderItem={item =>
                  item ? (
                    <List.Item key={item.id}>
                        <Card hoverable className={styles.card} actions={[]}>
                          <Card.Meta
                            avatar={<Avatar className={styles.cardAvatar}>{item.name.substr(0,1)} </Avatar>}
                            // title={<a>{item.name}</a>}
                            // description={
                            //     item.isUsed?
                            //       <Ellipsis className={styles.item} lines={3}>
                            //         <span style={{color:'skyblue'}} onClick={()=>this.showApiServiceConditionShow(item.id,item.name)}><Icon type="play-circle" className={styles.icon} />使用中</span>
                            //       </Ellipsis>
                            //       :''
                            // }
                          />
                          <div className={styles.cardHead}>
                              {
                                item.isUsed?
                                  <div>
                                    <span style={{color:'#4a4a4a',fontSize:'16px',}}>{item.name}</span>
                                    <Ellipsis className={styles.item} lines={3}>
                                    <span style={{color:'#9b9b9b',fontSize:'12px'}} onClick={()=>this.showApiServiceConditionShow(item.id,item.name)}><Icon type="play-circle" className={styles.icon} />使用中</span>
                                  </Ellipsis>
                                  </div>
                                  :
                                  <span>{item.name}</span>
                              }
                          </div>
                           <div className={styles.cardTool}>
                             <img src={editImg} alt="编辑知识点" style={{marginRight:5,cursor:"pointer"}} onClick={() => this.editApi(item.id)}  />
                             <img src={del1Img} alt="删除知识点" style={{marginRight:5,cursor:"pointer"}} onClick={() => this.delApi(item.id)} />
                           </div>
                        </Card>
                    </List.Item>
                  ) : (
                    <List.Item>
                      {/*<div  className={styles.newButton} onClick={()=>this.addApi()}>*/}
                      {/* <Icon type="plus" /> 添加接口*/}
                      {/*</div>*/}
                       <div className={styles.addButton}  onClick={()=>this.addApi()}>
                        <img  src={addJKImg}/>
                      </div>
                    </List.Item>
                  )
                }
              />
              <Pagination
                style={{ textAlign: 'center', marginTop: 20, marginBottom: 20 }}
                showSizeChanger
                total={parseInt(this.state.total)}
                current={this.state.page}
                onChange={e => this.fanye(e)}
                onShowSizeChange={(current, size) => this.pageSizeChange(current, size)}
                showTotal={() => `共 ${this.state.total} 条`}
              />

            </div>
            <ApiServiceCondition visible={apiServiceConditionShow} title={apiTitle} onClosed={()=>this.hideApiServiceConditionShow()} id={apiId} loading={apiLoading} />

        </Suspense>
      </GridContent>
    );
  }
}

export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(CustomApi);
